﻿using System.Security.Claims;
using BilbilBLL;
using BilbilDAL;
using Common;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using Modles.DTO;
using Modles.Models;

namespace bilbil.Controllers
{
    /// <summary>
    /// 个人主页功能
    /// </summary>
    /// 

    [Route("api/[controller]/[action]")]
    [ApiController]
    public class PersonalHomepageFunctionController : ControllerBase
    {
        PersonalHomepageFunctionServer server = new PersonalHomepageFunctionServer();
        /// <summary>
        /// 根据前端发送的用户信息表id查询并返回视频信息表，按视频发布时间降序排序，提供分页功能
        /// </summary>
        /// <param name="mod"></param>
        /// <param name="TotalCount"></param>
        /// <returns></returns>
        [HttpGet]
        [Authorize]
        public IActionResult GetReleaseVideoByuserId([FromQuery] ReleaseVideo_DTO model)
        {
            int userInfoId = Convert.ToInt32(User.FindFirst(ClaimTypes.NameIdentifier)?.Value);
            ResponseTool res = server.GetReleaseVideoByuserId(userInfoId, model.page, model.limit);
            return new JsonResult(new
            {
                code = res.code,
                msg = res.Message,
                data = res.data
            });
        }

        /// <summary>
        /// 根据前端发送的用户信息表id查询并返回动态表，按发布时间降序排序
        /// </summary>
        /// <param name="userId"></param>
        /// <returns></returns>
        [HttpGet]
        public IActionResult GetDynamic([FromQuery] int userId)
        {
            ResponseTool res = server.GetDynamic(userId);
            return new JsonResult(new
            {
                code = res.code,
                msg = res.Message,
                data = res.data
            });
        }

        /// <summary>
        /// 根据前端发送的用户信息表id查询并返回收藏表，按发布时间降序排序
        /// </summary>
        /// <param name="userInfoId"></param>
        /// <param name="page"></param>
        /// <param name="limit"></param>
        /// <param name="totalCount"></param>
        /// <returns></returns>
        [HttpGet]
        [Authorize]
        public IActionResult GetCollectionList([FromQuery] int page, int limit)
        {
            int totalCount;
            int userInfoId = Convert.ToInt32(User.FindFirst(ClaimTypes.NameIdentifier)?.Value);
            ResponseTool res = server.GetCollectionList(userInfoId, page, limit, out totalCount);
            return new JsonResult(res);
        }


        /// <summary>
        /// 根据前端发送的用户信息表id和用户信息修改用户信息
        /// </summary>
        /// <param name="modify_DTO"></param>
        /// <returns></returns>
        [HttpPut]
        [Authorize]
        public IActionResult UserinfoModify([FromBody] UserInfoModify_DTO modify_DTO)
        {
            int userInfoId = Convert.ToInt32(User.FindFirst(ClaimTypes.NameIdentifier)?.Value);
            modify_DTO.Id = userInfoId;
            ResponseTool res = server.UserinfoModify(modify_DTO);
            return new JsonResult(res);
        }
        /// <summary>
        /// 根据用户信息id获取用户关注人数和被关注人数
        /// </summary>
        /// <param name="UserInfoId"></param>
        /// <returns></returns>
        /// 
        [HttpGet]
        [Authorize]
        public IActionResult GetConcernList()
        {
            int UserInfoId = Convert.ToInt32(User.FindFirst(ClaimTypes.NameIdentifier)?.Value);
            return new JsonResult(server.GetConcernList(UserInfoId));
        }
        /// <summary>
        /// 根据用户信息id获取用户数据总览
        /// </summary>
        /// <param name="UserInfoId"></param>
        /// <returns></returns>
        /// 
        [HttpGet]
        [Authorize]
        public IActionResult GetDataOverview()
        {
            int UserInfoId = Convert.ToInt32(User.FindFirst(ClaimTypes.NameIdentifier)?.Value);
            return new JsonResult(server.GetDataOverview(UserInfoId));
        }
        /// <summary>
        /// 上传视频
        /// </summary>
        /// <param name="videoData">视频信息</param>
        /// <returns>上传结果</returns>
        [HttpPost]
        [RequestSizeLimit(1073741824)] // 1GB
        [RequestFormLimits(MultipartBodyLengthLimit = 1073741824)] // 1GB
        [Authorize]
        public async Task<IActionResult> AddVideoInfo([FromForm] VideoUploadRequest videoData)
        {
            try
            {
                Console.WriteLine($"收到视频上传请求 - 标题: {videoData?.Title}");

                // 参数验证
                if (videoData == null)
                {
                    return BadRequest(new { success = false, message = "请求数据为空" });
                }

                // 从 JWT 令牌中获取用户ID
                var userIdClaim = User.FindFirst(ClaimTypes.NameIdentifier)?.Value;
                int userId;

                if (string.IsNullOrEmpty(userIdClaim) || !int.TryParse(userIdClaim, out userId))
                {
                    // 如果 JWT 中没有用户ID，使用传入的用户ID
                    userId = videoData.UserInfoId;
                }

                if (userId <= 0)
                {
                    return BadRequest(new
                    {
                        success = false,
                        message = "无法获取用户信息"
                    });
                }

                // 验证必需字段
                if (string.IsNullOrEmpty(videoData.Title))
                {
                    return BadRequest(new { success = false, message = "视频标题不能为空" });
                }

                if (videoData.VideoTypeId <= 0)
                {
                    return BadRequest(new { success = false, message = "请选择视频类型" });
                }

                if (videoData.VideoFile == null || videoData.VideoFile.Length == 0)
                {
                    return BadRequest(new { success = false, message = "请选择视频文件" });
                }

                if (videoData.ImageFile == null || videoData.ImageFile.Length == 0)
                {
                    return BadRequest(new { success = false, message = "请选择封面图片" });
                }

                // 创建 DTO 对象
                var videoDto = new VideoUpload_DTO
                {
                    Title = videoData.Title,
                    Briefintroduction = videoData.Description ?? "",
                    VideoTypeId = videoData.VideoTypeId,
                    UserInfoId = userId,
                    Labels = !string.IsNullOrEmpty(videoData.Labels) ?
                            videoData.Labels.Split(',') :
                            new string[0]
                };

                Console.WriteLine($"开始处理上传 - 视频文件: {videoData.VideoFile.FileName}, 大小: {videoData.VideoFile.Length}");

                var result = server.AddVideoInfo(videoDto, videoData.VideoFile, videoData.ImageFile);

                Console.WriteLine($"上传处理完成 - 结果: {result?.Success}");

                return new JsonResult(result);
            }
            catch (Exception ex)
            {
                Console.WriteLine($"上传视频时发生异常: {ex}");
                return StatusCode(500, new
                {
                    success = false,
                    message = "服务器内部错误：" + ex.Message
                });
            }
        }
        /// <summary>
        /// 根据用户信息id获取用户关注的视频数量
        /// </summary>
        /// <returns></returns>
        /// 
        [HttpGet]
        [Authorize]
        public IActionResult GetUserCollectionCount()
        {
            int userInfoId = Convert.ToInt32(User.FindFirst(ClaimTypes.NameIdentifier)?.Value);
            return new JsonResult(new PersonalHomepageFunctionServer().GetUserCollectionCount(userInfoId));
        }
        /// <summary>
        /// 获取被关注的人员信息
        /// </summary>
        /// <param name="userInfoId"></param>
        /// <returns></returns>
        [HttpGet]
        [Authorize]
        public IActionResult GetConcernUserInfos()
        {
            int userInfoId = Convert.ToInt32(User.FindFirst(ClaimTypes.NameIdentifier)?.Value);
            return new JsonResult(new PersonalHomepageFunctionServer().GetConcernUserInfos(userInfoId));
        }



        /// <summary>
        /// 添加关注
        /// </summary>
        /// <param name="UserInfoId"></param>
        /// <param name="ConcernUserInfoId"></param>
        /// <returns></returns>
        [HttpPost]
        [Authorize]
        public IActionResult AddConcern( int ConcernUserInfoId)
        {
            int UserInfoId = Convert.ToInt32(User.FindFirst(ClaimTypes.NameIdentifier)?.Value);
            return new JsonResult(new PersonalHomepageFunctionServer().AddConcern(UserInfoId, ConcernUserInfoId));
        }
        /// <summary>
        /// 取消关注
        /// </summary>
        /// <param name="UserInfoId"></param>
        /// <param name="ConcernUserInfoId"></param>
        /// <returns></returns>
        [HttpDelete]
        [Authorize]
        public IActionResult DeleteConcern(int ConcernUserInfoId)
        {
            int UserInfoId = Convert.ToInt32(User.FindFirst(ClaimTypes.NameIdentifier)?.Value);
            return new JsonResult(new PersonalHomepageFunctionServer().DeleteConcern(UserInfoId, ConcernUserInfoId));
        }


        /// <summary>
        /// 获取用户发布的所有视频
        /// </summary>
        /// <param name="userInfoId"></param>
        /// <returns></returns>
        [HttpGet]
        [Authorize]
        public IActionResult GetUserPublishVideoInfo()
        {
            int userInfoId = Convert.ToInt32(User.FindFirst(ClaimTypes.NameIdentifier)?.Value);
            return new JsonResult(new PersonalHomepageFunctionServer().GetUserPublishVideoInfo(userInfoId));
        }


        /// <summary>
        /// 删除用户发布的指定视频
        /// </summary>
        /// <param name="userInfoId"></param>
        /// <param name="videoInfoId"></param>
        /// <returns></returns>
        [HttpDelete]
        [Authorize]
        public IActionResult DeleteUserPublishVideoInfo(int videoInfoId)
        {
            int userInfoId = Convert.ToInt32(User.FindFirst(ClaimTypes.NameIdentifier)?.Value);
            return new JsonResult(new PersonalHomepageFunctionServer().DeleteUserPublishVideoInfo(userInfoId, videoInfoId));
        }
    }
}
